<template>
  <div class="upload-container">
    <el-button class="editor-custom-btn-container" size="mini" plain type="primary" @click="dialogVisible = true">
      上传图片
    </el-button>
    <el-dialog v-model="dialogVisible" title="上传图片">
      <el-upload
        :http-request="httpRequestOrder"
        :on-success="handleSuccess"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        :multiple="true"
        :file-list="initData.fileList"
        :show-file-list="true"
        class="editor-slide-upload"
        action
        list-type="picture-card"
      >
        <el-button size="small" type="primary">选择图片</el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import aliOss from '@/utils/alioss'
import util from '@haluo/util'

const props = defineProps({
  color: {
    type: String,
    default: '#1890ff'
  }
})
const initData = reactive({
  listObj: {},
  fileList: [],
  uploads: []
})
const dialogVisible = ref(false)

const checkAllSuccess = () => {
  return Object.keys(initData.listObj).every((item) => {
    return initData.listObj[item].hasSuccess
  })
}

const emits = defineEmits(['successCBK'])
const handleSubmit = () => {
  const arr = Object.keys(initData.listObj).map((v) => initData.listObj[v])
  if (!checkAllSuccess()) {
    ElMessage.info(
      'Please wait for all images to be uploaded successfully. If there is a network problem, please refresh the page and upload again!'
    )
    return
  }
  emits('successCBK', arr)
  // 暴露给子组件的数据
  initData.listObj = {}
  initData.fileList = []
  dialogVisible.value = false
}

// 多张图片批量上传处理
const httpRequestOrder = async (option) => {
  option.imageType = 'nowater' // 无水印
  option.quality = 1 // 不压缩
  initData.uploads = initData.uploads || []
  initData.uploads.push({
    fn: aliOss.ossUploadImage,
    option
  })
  util.tools.debounce(call, 100)()
}

const call = async () => {
  for (const a of initData.uploads) {
    await a.fn(a.option)
  }
  initData.uploads = []
}

// 上传成功回调
const handleSuccess = (response, file) => {
  const uid = file.uid
  console.log(response, 'response==')
  const objKeyArr = Object.keys(initData.listObj)
  for (let i = 0, len = objKeyArr.length; i < len; i++) {
    if (initData.listObj[objKeyArr[i]].uid === uid) {
      initData.listObj[objKeyArr[i]].imgOrgUrl = response.imgOrgUrl
      initData.listObj[objKeyArr[i]].imgUrl = response.imgUrl
      initData.listObj[objKeyArr[i]].hasSuccess = true
      return
    }
  }
}

const handleRemove = (file) => {
  const uid = file.uid
  const objKeyArr = Object.keys(initData.listObj)
  for (let i = 0, len = objKeyArr.length; i < len; i++) {
    if (initData.listObj[objKeyArr[i]].uid === uid) {
      delete initData.listObj[objKeyArr[i]]
      return
    }
  }
}

const beforeUpload = (file) => {
  const _URL = window.URL || window.webkitURL
  const fileName = file.uid
  initData.listObj[fileName] = {}
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.src = _URL.createObjectURL(file)
    img.onload = function () {
      initData.listObj[fileName] = { hasSuccess: false, uid: file.uid, fileName: file.name, width: 200, height: 200 }
    }
    resolve(true)
  })
}
</script>

<style lang="scss" scoped>
.editor-custom-btn-container {
  position: absolute;
  top: 6px;
  right: 10px;
  z-index: 1003;
}

.editor-slide-upload {
  margin-bottom: 20px;

  ::v-deep .el-upload--picture-card {
    width: 100%;
  }
}
</style>
